847. Shortest Path Visiting All Nodes
847. Shortest Path Visiting All Nodes
Tag: State Compression, BFS, No AC first time
Description
Solutions
We can see from constrains that n<=12
, so we can use state compression. Also, the weight of each edge is 1, which reminds us of BFS to search for the lowest distance to reach final state 1<<n - 1
Some tricky points
- Use tuple to store a three tuple,
{node, mask, dist}
for the current node, mask and current distance. - Use a array or map to store the visited state, states should be distinct by their mask and current node.
Code
1 | class Solution { |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.